<template>
  <div class="functionEditor">
    {{editItem}}
    <xdh-form ref="form" class="rule-form" footer-align="right" inline-size="medium" label-width="80px" footer-size="large" :footer="true" size="small" :model="editItem" footer-border @submit="handleSubmit" :edits="true">
      <xdh-form-item v-for="item in formFields" :key="item.prop" v-bind="item" />
    </xdh-form>
  </div>
</template>
<style lang="stylus" rel="stylesheet/stylus" scoped type="text/stylus">
.functionEditor {
  width: 90%;
  margin: auto;

  .el-form-item {
    margin-bottom: 5px;
  }

  .functionInput {
    width: 100%;
  }

  .collapse {
    margin: auto;
    padding: 10px;
  }

  .tags {
    margin: 5px;
    cursor: pointer;
  }

  .params {
    border-top: 1px solid #ddd;
    padding-top: 10px;
    margin: 0px 10px;
    margin-top: 22px;
    position: relative;

    .tip {
      position: absolute;
      top: -22px;
      left: 20px;
      line-height: 18px;
      padding: 2px 10px 0;
      border: 1px solid #ddd;
      border-bottom: none;
    }
  }

  .form-item-label {
    font-size: 12px;
  }

  .desc {
    margin: 5px 10px;
  }
}
</style>

<script type="text/ecmascript-6">
import { mapGetters, mapState } from 'vuex'
import BaseComponent from '@/widgets/extend/BaseComponent'
import AttrData from '../attr/Data'
import cloneDeep from 'lodash/cloneDeep'

import XdhForm from '@/widgets/xdh-form'
import XdhFormItem from '@/widgets/xdh-form/xdh-form-item'

export default {
  name: 'FunctionEditor',
  components: { AttrData, XdhForm, XdhFormItem },
  mixins: [BaseComponent],
  props: {
    formFields: {
      type: Array,
      default: function() {
        return []
      }
    },
    editItem: {
      default:null,
    },
    rules:{
      type: Array,
      default: function() {
        return []
      }
    },
    index:{
      type: Number,
      default:0,
    }
  },
  data: function() {
    return {
      rules_s: this.rules,
    }
  },
  computed: {
    ...mapState(['editField']),
  },
  watch: {

  },
  mounted: function() {

  },
  methods: {
    cleanModel(model) {
        const m = {}
        Object.keys(model).forEach(key => {
          const val = model[key]
          if (typeof val !== 'undefined' && val !== '') {
            m[key] = val
          }
        })
        return m
      },
    handleSubmit(model) {
      const rule = this.cleanModel(model)
      const rules = [...this.rules]
      const index = rules.findIndex((item,index) => index === this.index)
      rules.splice(index, 1, rule)

    const newField = JSON.parse(JSON.stringify({
        ...this.editField,
        rules:rules
      }))
      // console.log(newField, 456789000000000)
      // this.$emit("update:rules",rules)
      this.$store.commit('updateField', newField)
    }
  }
}
</script>

